package com.demo.controller;

import com.aliyuncs.utils.StringUtils;
import com.demo.service.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyuan
 * @date 2020/10/28 10:51
 */
@RestController
@CrossOrigin // 跨域的支持
public class SmsApiController {
    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("send/{phone}")
    public String sendSms(@PathVariable("phone") String phoneNumber){
        // 调用发送发放（模拟真实业务，整合 Redis）

        // 判断当前手机号是否存储在 Redis 中
        // 如果没有则发送短信
        // 如果有表示上一个验证码还未过期，不用发送
        String code = (String) redisTemplate.opsForValue().get(phoneNumber);
        if (!StringUtils.isEmpty(code)){
            return "[手机号: "+phoneNumber + "],[验证码: " + code +"],还未过期";
        }

        // 生成验证码
        code = UUID.randomUUID().toString().substring(0,6);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);

        boolean isSend = sendSmsService.send(phoneNumber, "SMS_205138314", map);

        // 如果发送成功，就放入 Redis
        if (isSend){
            redisTemplate.opsForValue().set(phoneNumber,code,5, TimeUnit.MINUTES);
            return "[手机号: "+phoneNumber + "],[验证码: " + code +"],发送成功";
        }else {
            return "[手机号: "+phoneNumber + "],[验证码: " + code +"],发送失败";
        }

    }
}
